<?php

namespace addons\kuerp\model;

use addons\kuerp\model\Record as RecordModel;
use think\Exception;
use think\Model;
use think\Session;
use traits\model\SoftDelete;

/**
 *跟进记录
 */
class Record Extends Model {
	use SoftDelete;
    // 表名,不含前缀
    protected $name = 'kuerp_record';
	const   CUSTOMER_TYPE = 1;//客户
	const   CONTACTS_TYPE = 2;//联系人
	const   CONTRACT_TYPE = 3;//合同
	const   LEADS_TYPE    = 4;//线索
    const   BUSINESS_TYPE    = 5;//商机
	// 开启自动写入时间戳字段
	protected $autoWriteTimestamp = 'int';
	// 定义时间戳字段名
	protected $createTime = 'createtime';
	protected $updateTime = 'updatetime';
	protected $deleteTime = 'deletetime';


	//获取跟进记录列表
	public static function getList($relation_type, $relation_id) {
		return self::where(['relation_type' => $relation_type, 'relation_id' => $relation_id])->with(['file', 'staff'])->order('id desc')->select();
	}


	//销售
	public function staff() {
		return $this->hasOne(Staff::class, 'id', 'create_staff_id')->field('id,name')->removeOption('soft_delete');
	}

//创建人
    public function creatstaff() {
        return $this->hasOne(Admin::class, 'id', 'admin_id')->field('id,avatar,nickname')->removeOption('soft_delete');
    }
	//获取附件记录
	public function file() {
		return $this->hasMany(RecordFile::class, 'record_id', 'id')->with('file')->field('record_id,file_id');
	}


	//创建跟进记录
	public static function createRecord($params) {
		if(isset($params['files'])){
			$files = $params['files'];
			unset($params['files']);
		}else{
			$files='';
		}
        $staff  = Staff::info();
        if ($params['relation_type'] == RecordModel::CUSTOMER_TYPE) {//客户
            $create_staff_id = Customers::where(['id' => $params['relation_id']])->value('staff_member_id');

        } elseif ($params['relation_type'] == RecordModel::CONTACTS_TYPE) {//联系人
            $create_staff_id = 0;//CustomersUser::where(['id' => $params['relation_id']])->value('owner_staff_id');

        } elseif ($params['relation_type'] == RecordModel::CONTRACT_TYPE) {//合同
            $create_staff_id = GoodsSales::where(['id' => $params['relation_id']])->value('sale_user');

        }elseif ($params['relation_type'] == RecordModel::LEADS_TYPE) {//线索
            $create_staff_id = 0;//Leads::where(['id' => $params['relation_id']])->value('owner_staff_id');

        }elseif ($params['relation_type'] == RecordModel::BUSINESS_TYPE) {//
            $create_staff_id = 0;//Business::where(['id' => $params['relation_id']])->value('owner_staff_id');
        }
        // if(empty($create_staff_id)){
        //     $create_staff_id = $staff->id;
        // }
        if(isset($params['next_time'])){
            $params['next_time']=$params['next_time']?:NULL;
        }
		$params['create_staff_id'] = $create_staff_id;
        $params['admin_id'] = $staff->id;
		$params['follow_time']     = date('Y-m-d H:i:s');
		$model                     = new self;

        $result = $model->allowField(true)->save($params);
		$lastId=$model->getLastInsID();
		if (false === $result) {
			// 验证失败 输出错误信息
			throw new Exception($model->getError());
		}
		if ($files) {
			RecordFile::addFiles($files, $lastId);
		}

		if ($params['relation_type'] == RecordModel::CUSTOMER_TYPE) {//客户
		    if(isset($params['follow'])){
                $resCus['follow_status'] = $params['follow'];
            }
		    if(isset($params['next_time'])){
                $resCus['next_follow_time'] = strtotime($params['next_time']);
            }
            $resCus['last_follow_time'] = time();
			//同步跟进状态
			Customers::where(['id' => $params['relation_id']])->update($resCus);
			// if ($files) {
			// 	CustomerFile::addFiles($files, $params['relation_id']);
			// }
		} elseif ($params['relation_type'] == RecordModel::CONTACTS_TYPE && isset($params['next_time'])) {//联系人
			Contacts::where(['id' => $params['relation_id']])->update(['next_time' => $params['next_time']]);
			if ($files) {
				ContactsFile::addFiles($files, $params['relation_id']);
			}
		} elseif ($params['relation_type'] == RecordModel::CONTRACT_TYPE && isset($params['next_time'])) {//
			if ($files) {
				ContractFile::addFiles($files, $params['relation_id']);
			}
		}elseif ($params['relation_type'] == RecordModel::LEADS_TYPE && isset($params['next_time'])) {//
            Leads::where(['id' => $params['relation_id']])->update(['next_time' => $params['next_time']]);
			if ($files) {
				LeadsFile::addFiles($files, $params['relation_id']);
			}
		}elseif ($params['relation_type'] == RecordModel::BUSINESS_TYPE && isset($params['next_time'])) {//
            Business::where(['id' => $params['relation_id']])->update(['next_time' => $params['next_time']]);
        }
		//通知上级
		if($staff->parentids && !in_array(2,$staff->group_ids)) {
			foreach ($staff->parentids as $parent) {
				Message::addMessage(Message::RECORD_TYPE, $lastId, $parent, $staff->id);
			}
		}
		// if (isset($params['reminds_id'])) {//发送通知
		// 	$staff_ids = explode(',', $params['reminds_id']);
		// 	foreach ($staff_ids as $staff_id) {
		// 		//发送通知
		// 		Message::addMessage(Message::RECORD_TYPE, $lastId, $staff_id, $staff->id);
		// 	}
		// }

		return true;
	}


	//快速创建跟进记录
	public static function quickCreateRecord($type, $id, $content) {
		$follow_type = '其它';
		$staff=Staff::info();
		if(empty($staff)){
			return true;
		}
		$data = [
			'relation_type' => $type,
			'relation_id'   => $id,
			'content'       => $content,
			'follow_type'   => $follow_type,
			'follow_time'   => date('Y-m-d H:i:s'),
		];

		return self::createRecord($data);
	}

	public function read(){
		return $this->hasMany(RecordRead::class, 'record_id', 'id')->field('record_id,createtime');
	}
    //客户
    public function customer() {
        return $this->hasOne(Customers::class, 'id', 'relation_id')->field('id,name');
    }
    //线索
    public function leads() {
        return $this->hasOne(Leads::class, 'id', 'relation_id')->field('id,name');
    }
    //合同
    public function contract() {
        return $this->hasOne(GoodsSales::class, 'id', 'relation_id')->field('id,name');
    }
    //商机
    public function business() {
        return $this->hasOne(Business::class, 'id', 'relation_id')->field('id,name');
    }
}
